import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:gif/gif.dart';
import 'package:sports_new/controller/navigation_logic.dart';
import 'package:sports_new/controller/service/match_service.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/update_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/overlay/ads_float_widget.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/resource_dialog.dart';

import '../widgets/base/qkd_text.dart';

class NavigationPage extends StatefulWidget {
  const NavigationPage({super.key});

  // static callJump(String name) {
  //   _jump?.call(name);
  // }

  @override
  State<NavigationPage> createState() => _NavigationPageState();
}

class _NavigationPageState extends State<NavigationPage> {
  final logic = Get.put(NavigationLogic());

  static const double iconSize = 26.0;
  static const double fontSize = 10.0;

  //左划退出
  DateTime? lastLeftSlide;

  // int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations(
      [
        DeviceOrientation.portraitUp, // 竖屏 Portrait 模式
        DeviceOrientation.portraitDown,
      ],
    );
    final matchService = Get.find<MatchService>();
    if (matchService.zqOneLevelLeague == null) {
      matchService.getZqOneLevelLeague();
    }
    if (matchService.lqOneLevelLeague == null) {
      matchService.getLqOneLevelLeague();
    }
    UpdateUtils.getInfo();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      AdsFloatWidget.checkAds(logic.currentRoute);
    });
    getWxInfo();
  }

  Future getWxInfo() async{
    Fluwx fluwx = Fluwx();
    weChatListener(response) {
      if(response is WeChatShowMessageFromWXRequest){
        if(response.extMsg.hasValue && response.extMsg!.contains("{")) {
          Utils.doJump(response.extMsg!);
        }
      }
    }
    fluwx.addSubscriber(weChatListener);
    fluwx.attemptToResumeMsgFromWx();
  }

  @override
  Widget build(BuildContext context) {
    ResourceDialogUtil.checkShowDialog(
        curRoute: NavigationLogic.homeRoutes[logic.currentIndex]);
    // AdsFloatWidget.checkAds(NavigationLogic.homeRoutes[logic.currentIndex]);
    return WillPopScope(
      onWillPop: () async {
        if (lastLeftSlide == null ||
            DateTime.now().difference(lastLeftSlide!) >
                const Duration(milliseconds: 1500)) {
          lastLeftSlide = DateTime.now();
          ToastUtils.showDismiss('再按一次退出球客岛', 1);
          return Future.value(false);
        } else {
          lastLeftSlide = DateTime.now();
          // 退出app
          return Future.value(true);
        }
      },
      child: GetBuilder<NavigationLogic>(
        builder: (_) {
          return Scaffold(
            bottomNavigationBar: Container(
              decoration: BoxDecoration(
                boxShadow: const [
                  BoxShadow(
                    color: Color(0x0C0F499F),
                    offset: Offset(0, -2),
                    blurRadius: 12,
                  )
                ],
                image: logic.backgroundImage == null ? null
                  : DecorationImage(
                    fit: BoxFit.cover,
                    image: CachedNetworkImageProvider(logic.backgroundImage!),
                  ),
              ),
              child: BottomNavigationBar(
                // backgroundColor: Theme.of(context).,
                items: _navigationItems(context),
                type: BottomNavigationBarType.fixed,
                currentIndex: logic.currentIndex,
                elevation: 0,
                selectedFontSize: fontSize,
                unselectedFontSize: fontSize,
                selectedItemColor: Colours.main,
                unselectedItemColor: Colours.text,
                // selectedLabelStyle: TextStyle(height: 1.1),
                // showSelectedLabels: false,
                backgroundColor: logic.backgroundImage == null
                    ? Colours.white
                    : Colors.transparent,
                onTap: (index) {
                  logic.getRoute();
                  logic.onTapIndex(index);
                },
              ),
            ),
            body: Stack(
              children: [
                PageView(
                  physics: const NeverScrollableScrollPhysics(),
                  controller: logic.pageController,
                  onPageChanged: (int index) {
                    setState(() {
                      logic.currentIndex = index;
                    });
                    logic.getRoute();
                  },
                  children: logic.pageList,
                ),
                if (!User.isLogin && logic.showLoginFloat && !logic.ignoreLogin.contains(logic.currentRoute))
                  Positioned(
                      left: 8, right: 8, bottom: 16, child: loginFloatWidget()
                  ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget loginFloatWidget() {
    log('User.isLogin ${User.isLogin}');
    return Container(
      height: 48,
      padding: const EdgeInsets.only(left: 16, right: 8),
      decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.7),
          borderRadius: BorderRadius.circular(24)),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              logic.showLoginFloat = false;
              update();
            },
            child: Padding(
              padding: const EdgeInsets.all(4),
              child: Image.asset(
                Utils.getImgPath('close_48.png'),
                width: 16,
              ),
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Image.asset(
                  Utils.getImgPath('gift_icon.png'),
                  width: 40,
                ),
                const SizedBox(width: 4),
                const QkdText(
                  '立即登录，解锁全部功能',
                  color: Colours.white, fontWeight: FontWeight.w500
                ),
                const Spacer(),
                QkdButton(
                  text: '去登录',
                  width: 80,
                  height: 32,
                  textStyle: const TextStyle(fontSize: 14),
                  backgroundColor: Colours.main,
                  foregroundColor: Colours.white,
                  onPressed: () => Utils.login()
                )
              ],
            ).tap(() => Utils.login()),
          ),
        ],
      ),
    );
  }

  List<BottomNavigationBarItem> _navigationItems(context) {
    List<List<Widget>> items = [];
    for (int i = 0; i < logic.navIcons.length; i++) {
      if (NavigationLogic.homeRoutes[i] == Routes.match && logic.matchScroll && !logic.selectArray[i].endsWith("gif")) {
        items.add([
          Gif(
            image: AssetImage(Utils.getFilePath('refresh.gif')),
            width: logic.iconWidth ?? iconSize,
            height: logic.iconHeight ?? iconSize,
            autostart: Autostart.no,
            controller: logic.refreshC),
          logic.navIcons[i].last
        ]);
      } else {
        items.add(List.from(logic.navIcons[i]));
      }
    }
    if (logic.firstLoad && logic.firstSelectImage != null) {
      //gif加载过慢,第一次加载用图片
      items[logic.currentIndex][0] = logic.firstSelectImage!;

      logic.firstLoad = false;
    }
    return List.generate(logic.navIcons.length, (i) {
      return BottomNavigationBarItem(
        // tooltip: '',
        icon: items[i][1],
        activeIcon: items[i][0],
        label: logic.titles[i],
      );
    });
  }
}
